package com.tim.app.db.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.application.library.log.DLOG;
import com.tim.app.db.model.NoticeModel;


public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "jasmine";

    public static final int DATABASE_VERSION = 2;

    private SQLiteDatabase db;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.beginTransaction();
        try {
            db.execSQL(NoticeModel.CREATE_SQL);

            db.setTransactionSuccessful();
        } catch (SQLException e) {
            DLOG.e("Error creating tables and debug data", e.toString());
            throw e;
        } finally {
            db.endTransaction();
        }
    }

    public static String[] getTableNames() {

        return new String[]{NoticeModel.TABLE_NAME};
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.beginTransaction();
        try {
            for (String tableName : getTableNames()) {
                db.execSQL("DROP TABLE IF EXISTS " + tableName);
            }
            onCreate(db);
            db.setTransactionSuccessful();
        } catch (SQLException e) {
            DLOG.e("Error creating tables and debug data", e.toString());
            throw e;
        } finally {
            db.endTransaction();
        }
    }

    public DBHelper open() throws SQLException {
        db = this.getWritableDatabase();
        return this;
    }

    public DBHelper openReadable() throws SQLException {
        db = this.getReadableDatabase();
        return this;
    }

    public DBHelper openWritable() throws SQLException {
        db = this.getWritableDatabase();
        return this;
    }

    public void close() {
        if (db != null) {
            db.close();
        }
    }

    public Cursor rawQuery(String sql, String[] selectionArgs) {
        return db.rawQuery(sql, selectionArgs);
    }

    public boolean delete(String table, String whereClause, String[] whereArgs) {
        return db.delete(table, whereClause, whereArgs) > 0;
    }

    public long insert(String table, String nullColumnHack, ContentValues cv) {
        return db.insert(table, nullColumnHack, cv);
    }

    public int update(String table, ContentValues cv, String whereClause,
                      String[] whereArgs) {
        return db.update(table, cv, whereClause, whereArgs);
    }

    public void execSql(String sql) {
        db.execSQL(sql);
    }
}
